<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { showConfirmDialog, showToast } from "vant";
import { useRouter } from 'vue-router';
import { iuserInfo, iuserRegister, iuserPhonecode, space2userApi, iuserPhonenocodelogin, space2userById, iuserApi, iuserById } from '@/service/api.ts';
import { Md5 } from 'ts-md5';
import { useConstValue, useLocalValue, useIuserInfoStore } from '@/store/users.ts';
import { deepCopy } from '@/utils/utils.ts'
import AttentionSvg from '~icons/svg/attention';

const router = useRouter();
const constValue = useConstValue();
const localValue = useLocalValue();
const iuserInfoStore = useIuserInfoStore();

const props = defineProps({
  phone: { type: String, required: true },
  roomCode: { type: String, required: true },
});

onMounted(() => {
  localValue.setR_id(props.roomCode);
  init();
});

const userRt = reactive({
  actionSheet: false,
  act_type: '',
  
  mainUser: null,
  showPhoneQusetion: false,
})
const init = async () => {
  const space2user = await getSpace2userByRoomCode();

  
  /* 除了4-101，不存在没业主的楼室号 */
  if (!space2user.length) {
    showToast(`未知故障，请联系物业！`);
    return;
  }
  iuserInfoStore.userSystemInfo = space2user[0]
  /* 确定当前楼室号的业主是谁 */
  userRt.mainUser = space2user.find(i => i.type === '业主');
  if (!userRt.mainUser) {
    showToast('未查询到当前楼室号的业主，请联系物业！');
    return;
  }
  /* 储存当前房间业主信息 */
  
  localValue.setMainUser(deepCopy(userRt.mainUser));
  
  /* 当前手机号对应space2user */
  const currentInfo = space2user.find(i => i.user_auth_user_username === props.phone);
  
  /* 如果不存在则录入当前手机号 */
  if (!currentInfo) {
    userRt.actionSheet = true;
    return;
  }
  
  /* 如果是租客，则提示无法参与投票 */
  if (currentInfo.type === '租客') {
    showToast('您没有权限参与投票！');
    return;
  }
  
  const loginSuccess = await goToLogin();
  if (!loginSuccess) {
    showToast('登陆失败！');
    return;
  }
  checkLoginSuccess();
}
const getSpace2userByRoomCode = () => {
  return new Promise((resolve, reject) => {
    space2userApi({
      method: 'get',
      params: {
        project: constValue.projectID,
        space__r_id: props.roomCode,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      resolve([]);
    })
  })
}
const checkLoginSuccess = async () => {
  const info = await getIuserInfo();
  if (!info) {
    showToast('登陆失败，请尝试重新登陆！');
    return;
  }
  iuserInfoStore.setIuserInfo(info);
  router.push({ path: '/businessCommittee' });
}
const goToLogin = () => {
  return new Promise((resolve, reject) => {
    iuserPhonenocodelogin({
      method: 'post',
      data: {
        phone: props.phone,
        project: constValue.projectID,
      }}).then(res => {
        resolve(true);
      }).catch(err => {
        resolve(false);
      })
  })
}
const getIuserInfo = () => {
  return new Promise((resolve, reject) => {
    iuserInfo({
      method: 'get',
    }).then(res => {
      resolve(res);
    }).catch(err => {
      resolve(null);
    });
  })
}

/* 录入信息 */
const dialogRt = reactive({
  show: false,
  iuser: null,
  checkFalse: false,
  isCode: false,
})
const handleSubmit = async (type) => {
  if (!type) {
    showToast('请选择您和业主的关系！');
    return;
  }
  
  /* 调取数据库看该手机号用户是否存在 */
  const iusers = await searchIuser(props.phone);
  let [ iuser ] = iusers;
  if (iuser && !iuser.company) {
    // iuserById
  }
  
  dialogRt.iuser = iuser || null;
  
  dialogRt.show = true;
  setTimeout(() => {
    codeRef.value[0]?.focus(); // 初始化时聚焦第一个输入框
  }, 30);
  
  
}
const searchIuser = (phoneStr) => {
  return new Promise((resolve, reject) => {
    iuserApi({
      method: 'get',
      params: {
        search: phoneStr,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      resolve([]);
    })
  })
}

const codeLength = 4; // 尾号长度
const code = reactive(new Array(codeLength).fill('')); // 尾号存储
const codeRef = ref([]);
const handleInput = (index) => {
  dialogRt.checkFalse = false;
  const value = code[index];
  if (!/^\d$/.test(value)) {
    code[index] = ''; // 非数字清空
    return;
  }
  if (index >= codeLength - 1) {
    // 最后一个框
    return;
  }
  codeRef.value[index + 1]?.focus();
}
const handleBackspace = (index) => {
  dialogRt.checkFalse = false;
  if (index > 0 && !code[index]) {
    // 当前框为空，退回到前一个框，同时清空前一个框的值
    codeRef.value[index - 1]?.focus();
    code[index - 1] = '';
  } else {
    code[index] = ''; // 清空当前输入框的值
  }
}
const handleCancel = () => {
  dialogRt.show = false;
  dialogRt.checkFalse = false;
  dialogRt.isCode = false;
}
const phoneSubmit = () => {
  const enteredCode = code.join('');
  const next4 = userRt.mainUser.user_auth_user_username.substr(-4,4);
  dialogRt.checkFalse = next4 !== enteredCode;
  if (dialogRt.checkFalse) {
    return;
  }
  if (!dialogRt.iuser) {
    dialogRt.isCode = true;
    for(let i = 0; i < codeLength; i++) {
      code[i] = '';
    }
    setTimeout(() => {
      codeRef.value[0]?.focus(); // 初始化时聚焦第一个输入框
    }, 30);
    /* 发送验证码 */
    iuserPhonecode({
      method: 'post',
      data: {
        phone: props.phone,
      },
    })
    return;
  }
  submitCheckOK();
}

const submitCheckOK = async () => {
  dialogRt.show = false;
  const loginSuccess = await goToLogin();
  if (!loginSuccess) {
    showToast('登陆失败！');
    return;
  }
  if (userRt.act_type === '业主') {
    /* 替换掉原业主 */
    space2userById({
      method: 'patch',
      id: userRt.mainUser.id,
      data: {
        user: dialogRt.iuser.id,
      }
    }).then(res => {
      showToast('关联成功！');
      checkLoginSuccess();
    }).catch(err => {
      showToast('关联失败，请联系物业！');
    });
  } else {
    /* 家属或租客，创建一条家属租客信息 */
    space2userApi({
      method: 'post',
      data: {
        project: constValue.projectID,
        space: userRt.mainUser.space,
        type: userRt.act_type,
        user: dialogRt.iuser.id,
      }
    }).then(res => {
      showToast('关联成功！');
      if (userRt.act_type === '租客') {
        showToast('您没有权限参与投票！');
      } else {
        checkLoginSuccess();
      }
    }).catch(err => {
      showToast('关联失败，请联系物业！');
    });
  }
}
const codeSubmit = async () => {
  const enteredCode = code.join('');
  const flag = await registerIuser(enteredCode);
  dialogRt.checkFalse = !flag;
  if (!flag) {
    showToast('验证失败！');
    return;
  }
  const iusers = await searchIuser(props.phone);
  let [ iuser ] = iusers;
  if (!iuser) {
    showToast('未知故障，请联系物业！');
    return;
  }
  dialogRt.iuser = iuser;
  submitCheckOK();
}
const registerIuser = (codestr) => {
  return new Promise((resolve, reject) => {
    iuserRegister({
      method: 'post',
      data: {
        phone: props.phone,
        code: codestr,
        password: Md5.hashStr('.ieieye.com' + props.phone.substr(-6, 6) + 'shhengji'),
        identity: userRt.act_type,
        type: '项目用户',
        company: constValue.companyID,
        project: constValue.projectID,
      },
    }).then(res => {
      resolve(true);
    }).catch(err => {
      resolve(false);
    });
  })
}
// const checkOK = async () => {
//   /* 调取数据库看该手机号用户是否存在 */
//   const iusers = await searchIuser(props.phone);
//   let [ iuser ] = iusers;
  
//   if (!iuser) {
//     /* 新增用户 */
//     let auth_user_w = {
//       password: Md5.hashStr('.ieieye.com' + props.phone.substr(-6, 6) + 'shhengji'),
//       username: props.phone,
//     };
//     const response = await iuserApi({
//       method: 'post',
//       data: {
//         // truename: '未知',
//         contract: props.phone,
//         auth_user_w,
//         company: constValue.companyID,
//         type: '项目用户',
//         projects: [constValue.projectID],
//       }
//     });
//     if (!response) {
//       showToast('关联失败，请联系物业！');
//       return;
//     }
//     iuser = response;
//   }
//   if (userRt.act_type === '业主') {
//     /* 替换掉原业主 */
//     space2userById({
//       method: 'patch',
//       id: userRt.mainUser.id,
//       data: {
//         user: iuser.id,
//       }
//     }).then(res => {
//       showToast('关联成功！');
//       window.location.reload();
//     }).catch(err => {
//       showToast('关联失败，请联系物业！');
//     });
//   } else {
//     /* 家属或租客，创建一条家属租客信息 */
//     space2userApi({
//       method: 'post',
//       data: {
//         project: constValue.projectID,
//         space: userRt.mainUser.space,
//         type: userRt.act_type,
//         user: iuser.id,
//       }
//     }).then(res => {
//       showToast('关联成功！');
//       window.location.reload();
//     }).catch(err => {
//       showToast('关联失败，请联系物业！');
//     });
//   }
// }
</script>

<template>
  <div>
    <van-action-sheet
      v-model:show="userRt.actionSheet"
      :close-on-click-overlay="false"
      :overlay-style="{ backgroundColor: 'rgba(0,0,0,0.02)' }"
    >
      <div class="content flex-column">
        <label class="qusetion">您和业主的关系</label>
        <van-radio-group v-model="userRt.act_type" direction="horizontal" shape="dot">
          <van-radio name="业主">我是业主</van-radio>
          <van-radio name="家属">家属</van-radio>
          <van-radio name="租客">租客</van-radio>
        </van-radio-group>
        
        <button @click="handleSubmit(userRt.act_type)">确认</button>
      </div>
    </van-action-sheet>
    
    <van-dialog v-model:show="dialogRt.show" :showConfirmButton="false">
      <div class="check-box flex-column">
        <header>验证{{ dialogRt.isCode ? '本人' : '业主' }}身份</header>
        <div class="flex--center" v-if="!dialogRt.isCode">
          <p>
            请输入{{ userRt.mainUser?.user_auth_user_username?.substr(0, 7) }}****后四位
          </p>
          <van-popover>
            <p class="question-pop">手机号码可能有误，若有疑问，请联系物业</p>
            <template #reference>
              <div class="description flex-center-center pointer">?</div>
            </template>
          </van-popover>
        </div>
        <p v-else>首次需要验证身份，请输入您收到的验证码</p>
        <div class="code-input flex-sb">
          <input
            ref="codeRef"
            v-for="(digit, index) in code"
            :key="index"
            type="text"
            maxlength="1"
            class="digit-input"
            v-model="code[index]"
            @input="handleInput(index)"
            @keydown.backspace.prevent="handleBackspace(index, $event)"
          />
        </div>
        
        <div class="checkFalse flex--center" v-if="dialogRt.checkFalse">
          <AttentionSvg color="#E70101" />
          {{ dialogRt.isCode ? '验证码' : '号码' }}输入错误
        </div>
        
        <div class="btns flex">
          <button @click="handleCancel()">取消</button>
          <button @click="phoneSubmit()" v-if="!dialogRt.isCode">{{ dialogRt.iuser ? '确认' : '下一步' }}</button>
          <button @click="codeSubmit()" v-else>确认</button>
        </div>
      </div>
    </van-dialog>
  </div>
  
</template>

<style lang="scss" scoped>
.content {
  height: 50vh;
  padding: 24px;
  position: relative;
}
label.qusetion {
  font-size: 16px;
  color: #333333;
  line-height: 19px;
  margin-bottom: 16px;
  position: relative;
  &:before {
    content: '*';
    position: absolute;
    left: -8px;
    top: 50%;
    transform: translateY(-50%);
    color: red;
  }
}
.content button {
  position: absolute;
  width: calc(100% - 48px);
  height: 44px;
  bottom: 20px;
  background: #009245;
  border-radius: 30px;
  border: none;
  line-height: 44px;
  color: #fff;
}

.check-box {
  header {
    font-weight: 500;
    font-size: 24px;
    color: #333333;
    height: 34px;
    line-height: 34px;
    margin-bottom: 3px;
  }
  p {
    font-size: 14px;
    color: #666666;
    height: 20px;
    line-height: 20px;
  }
  .description {
    position: relative;
    width: 20px;
    height: 20px;
    background-color: #888888;
    border-radius: 50%;
    color: #ffffff;
    margin-left: 5px;
  }
}

:deep(.question-pop) {
  font-weight: 400;
  font-size: 12px;
  color: #303133;
}
.code-input {
  margin-top: 16px;
}
.digit-input {
  background-color: #fff;
  width: 50px;
  height: 50px;
  text-align: center;
  border: 1px solid #D9D9D9;
  border-radius: 4px;
  font-weight: 500;
  font-size: 24px;
  color: #000000;
}
.digit-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 3px rgba(0, 123, 255, 0.5);
}

.checkFalse {
  margin-top: 4px;
  font-size: 14px;
  color: #E70101;
  svg {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
}

.btns {
  position: absolute;
  width: calc(100% - 48px);
  bottom: 24px;
  gap: 8px;
  button {
    width: 100%;
    background-color: #009245;
    border: 1px solid #009245;
    border-radius: 30px;
    font-weight: 400;
    font-size: 14px;
    padding: 12px 0;
    color: #FFFFFF;
  }
  button:nth-child(1) {
    border-color: #E5E5E5;
    background-color: transparent;
    color: #000;
  }
}

</style>

<style scoped>
:deep(.van-radio__icon--dot) {
  width: 14px;
  height: 14px;
}
:deep(.van-radio-group) {
  justify-content: space-between;
}
:deep(.van-radio__label) {
  font-size: 14px;
  color: #111111;
  line-height: normal;
}

:deep(.van-dialog) {
  border-radius: 4px;
  padding: 24px;
  margin: auto 12px;
  width: auto;
  min-height: 300px;
}
:deep(.van-popover__content) {
  border-radius: 4px;
  padding: 6px 12px;
}
</style>